package April._25.homework.work2;

import code._15network.tcp.v3.Student;

import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Main {
    String targetClass;
    String fieldName;
    int newValue;

    public Main(String targetClass, String fieldName, int newValue) {
        this.targetClass = targetClass;
        this.fieldName = fieldName;
        this.newValue = newValue;
    }

    public static void main(String[] args) {
        String name="name";
        TargetObj targetObj=new TargetObj();
        String newValue="zs";
        try {
            serAll(targetObj,name,newValue);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    public static void serAll(Object targetObj, String fieldName, Object newValue) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> aClass = targetObj.getClass();
        //获取成员变量
        Field declaredField = aClass.getDeclaredField(fieldName);
        //获取构造器
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
/*        //对象实例化
        Object o = declaredConstructor.newInstance();*/
        //忽略Java语法检查、避免该成员是私有的
        declaredField.setAccessible(true);
        //设置值
        declaredField.set(targetObj,newValue);
        System.out.println(targetObj);
    }
}

class TargetObj{
    private String name;

    @Override
    public String toString() {
        return "TargetObj{" +
                "name='" + name + '\'' +
                '}';
    }
}
